package com.qfedu.buy.server.listener;

import com.qfedu.buy.common.config.RabbitMQConstantConfig;
import com.qfedu.buy.common.config.SystemConfig;
import com.qfedu.buy.common.dto.UserScoreDto;
import com.qfedu.buy.server.dao.UserlevelDao;
import com.qfedu.buy.server.entity.Userlevel;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @program: NeighborBuy
 * @description:
 * @author: Feri(邢朋辉)
 * @create: 2021-01-26 15:04
 */
@Component
@RabbitListener(queues=RabbitMQConstantConfig.QUEUE_USER_LEVEL_SOCRE)
public class UserLevelChangeListener {
    @Autowired
    private UserlevelDao userlevelDao;
    @RabbitHandler
    public void handler(UserScoreDto dto){
        Userlevel userlevel=userlevelDao.selectByUid(dto.getUid());
        //校验等级是否会变化
        if(userlevel!=null){
            int s=userlevel.getScore()+dto.getScore();
            userlevel.setScore(s);
            //<100 <1000 <10000 <100000 <1000000
            int lev=0;
            //88 188
            //计算积分对应的等级
            for(int i=1;i<6;i++){
                if(s/Math.pow(10,i+1)<1){
                    lev=i;
                    break;
                }
            }
            if(userlevel.getLevel()==lev){
                //等级没有变化
                userlevelDao.update(userlevel);
            }else{
                //等级提升了
                userlevel.setLevel(lev);
                userlevel.setLname(SystemConfig.levelMap.get(lev));
                userlevelDao.updateLevel(userlevel);
            }
        }

    }
}
